import { useGlobalStore, useMenuStore } from '@/store'
import type { Router, RouteRecordRaw } from 'vue-router'
import { NAME_STARTUP } from '../constants'

import Template from '@/pages/startup/template/index.vue'

export default function setupDynamicRouteGuard(router: Router) {
  router.beforeEach((to) => {
    if (router.hasRoute(to.name as string)) return true

    if (!to.name && to.path.startsWith(`/${NAME_STARTUP}/`)) {
      const route = createRoute(to.query as ClickableMenuItem)
      router.addRoute(NAME_STARTUP, route)

      const { createdMap } = toRefs(useMenuStore())
      createdMap.value[to.path] = true

      return { path: to.path, query: { ...to.query } }
    }

    return true
  })
}

const createRoute = (meta: ClickableMenuItem): RouteRecordRaw => {
  return {
    path: `/${NAME_STARTUP}/${meta.key}`,
    name: meta.key,
    component: () => import('@/pages/startup/template/index.vue'),
    meta
  }
}
